require "csv"
require 'digest/md5'


class EventsController < ApplicationController
  # GET /events
  # GET /events.xml
  def index
    @events = Event.find(:all, :conditions => {:user_id => current_user.id})
    logger.debug "events : " + @events.inspect

    respond_to do |format|
      format.html # index.html.erb
      format.xml # index.xml.erb
    end
  end

  # GET /events/1
  # GET /events/1.xml
  # GET /events/1.csv
  def show
    @event = Event.find(params[:id])
    @visitors = @event.visitors

    respond_to do |format|
      format.html # show.html.erb
      format.xml # show.xml.erb
      format.csv # show.csv.erb
    end
  end
  
  # GET /events/new
  # GET /events/new.xml
  def new
    @event = Event.new

    respond_to do |format|
      format.html # new.html.erb
      format.xml  { render :xml => @event }
    end
  end

  # POST /events/choose
  # POST /events/choose.xml
  def choose
    @event = Event.new

    # 引き回し
    @csv = params[:csv]

    # ヘッダーのみ解析
    tempCsv = CSV::StringReader.new(@csv)
    csvHeader = tempCsv.shift
    logger.debug "parsed CSV header : " + csvHeader.inspect
    @header = [["なし", -1]]
    i = 0
    # option用に詰める
    csvHeader.each do |value|
      @header << [value, i]
      i += 1
    end
    
    respond_to do |format|
      format.html # choose.html.erb
      format.xml  { render :xml => @event }
    end
  end

  # POST /events
  # POST /events.xml
  def create
    @event = Event.new(params[:event])
    @event.user_id = current_user.id

    pickParams = {:name => params[:name_column], :mail => params[:mail_column], :number => params[:number_column]}
    

    respond_to do |format|
      if @event.save and parseEvent(params[:csv], @event, pickParams)
        flash[:notice] = 'Event was successfully created.'
        format.html { redirect_to(@event) }
        format.xml  { render :xml => @event, :status => :created, :location => @event }
      else
        format.html { render :action => "new" }
        format.xml  { render :xml => @event.errors, :status => :unprocessable_entity }
      end
    end
  end

  # PUT /events/1
  # PUT /events/1.xml
  def update
    success_all = true
    unless params[:userid].nil? and Array != params[:userid].class
      params[:userid].each do |key, value|
        visitor = Visitor.find(:first, :conditions => {:event_id => params[:id], :user_hash => value})
        if visitor.nil?
          success_all = false
        else
          visitor.came_at = Time.now
          success_all = false unless visitor.save
        end
      end
    else
      success_all = false
    end

    # 結果を確認用
    @event = Event.find(params[:id])
    @visitors = @event.visitors

    respond_to do |format|
      if success_all
        format.html { redirect_to(@event) }
        format.xml  { render :action => "show" }
      else
        format.html { render :action => "new" }
        format.xml  { render :xml => @event.errors, :status => :unprocessable_entity }
      end
    end
  end

  # DELETE /events/1
  # DELETE /events/1.xml
  def destroy
    @event = Event.find(params[:id])
    @event.destroy

    respond_to do |format|
      format.html { redirect_to(events_url) }
      format.xml  { head :ok }
    end
  end

  
private

  # seminorParams = [{:name => "ルームA 13:00〜", :colNum => 5}, {:name => "", :colNum => 6}]
  # pickparams = {:name => 1, :mail => 2, :number => 3}
  def parseEventAndSeminor(csvString, eventAR, seminarParams, pickParams)

    # セミナー登録
    seminarParams.each do |param|
      eventAR.seminars.create(:name => param[:name])
    end
    seminars = eventAR.seminars.find(:all)
    
    parseCsv(csvString, eventAR, pickParams) do |csv, row, name, mail, number, user_hash|
      eventAR.visitors.create(:csv => csv, :name => name, :mail => mail, :number => number, :user_hash => user_hash)
      
      seminars.each do |seminor|
        # ToDo:セミナーの参加条件を確認して、登録
        
      end
    end

    return true
  end
  
  # pickparams = {:name => 1, :mail => 2, :number => 3}
  def parseEvent(csvString, eventAR, pickParams)
    
    parseCsv(csvString, eventAR, pickParams) do |csv, row, name, mail, number, user_hash|
      logger.debug "return from parseCSV csv : " + csv + " / name : " + name + " / mail : " + mail + " / number : " + number + " / user_hash : " + user_hash
      eventAR.visitors.create(:csv => csv, :name => name, :mail => mail, :number => number, :user_hash => user_hash)
    end

    return true
  end

  def parseCsv(csvString, eventAR, pickParams)
    csv = CSV::StringReader.new(csvString)
    csvLines = []
    csvString.each_line do |line|
      csvLines << line
    end
    eventAR.csv_header = csvLines[0]
    eventAR.save

    logger.debug "pickParams : " + pickParams.inspect
    header = csv.shift
    i = 0
    userCheckArray = []
    csv.each do |row|
      i += 1
      name = ""
      mail = ""
      number = ""
      pickParams.each do |key, colNum|
        logger.debug "param key : " + key.to_s + " / colNum : " + colNum.to_s + " / row : " + row.inspect
        case key
        when :name then name = row[colNum.to_i] unless colNum == "-1"
        when :mail then mail = row[colNum.to_i] unless colNum == "-1"
        when :number then number = row[colNum.to_i] unless colNum == "-1"
        end
      end
      userCheckHash = Digest::MD5.hexdigest(csvLines[i]).to_s
      # 重複チェック
      unless userCheckArray.include?(userCheckHash)
        userCheckArray << userCheckHash
        yield(csvLines[i], row, name, mail, number, userCheckHash)
      end
    end
  end

end
